<template>
    <el-select v-model="user" :multiple="multiple" clearable filterable placeholder="请选择" style="width: 100%" @change="handleChange">
        <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
</template>

<script>
import { OrgModel } from '@/models'

export default {
    name: 'UserSelect',
    props: {
        multiple: {
            type: Boolean,
            default: false
        },
        value: {
            type: [Array, Number, String],
            default: null
        },
        id: {
            type: [Number, String],
            default: 0
        },
        isAll: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            model: new OrgModel(),
            user: this.value,
            userOptions: []
        }
    },
    watch: {
        value(newValue) {
            this.user = newValue
        },
        id: {
            immediate: true,
            handler(newValue) {
                newValue && this.getUserByOrg()
            }
        },
        isAll: {
            immediate: true,
            handler(newValue) {
                newValue && this.getAllUser()
            }
        }
    },
    methods: {
        handleChange(value) {
            this.$emit('update:value', value)
            // 用户名拾取
            const curUser = this.userOptions.find(el => el.value === value)
            if (curUser) {
                this.$emit('update:name', curUser.label)
            }
        },
        // 获取机构下人员
        getUserByOrg() {
            this.model.detail(this.id, { pageSize: 1000 }).then((res = []) => {
                this.userOptions = res.map((item) => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
            })
        },
        // 获取所有养护的人员
        getAllUser() {
            this.model.getAllUser().then((res = []) => {
                this.userOptions = res.map((item) => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
            })
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
